# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: inkyu

import datetime
import sys

import coin.flow.subscriber as flow_subscriber
from coin.exchange.bitmex.kr_rest.futures_product import BitmexFuturesProduct
from coin.exchange.bitmex.ws.handler import BitmexHandler


def handle_book(book):
  bid0_p = book.bid0().price
  bid0_q = book.bid0().qty
  ask0_p = book.ask0().price
  ask0_q = book.ask0().qty
  print('"BOOK",%d,%f,%f,%f,%f' % (book.timestamp, bid0_p, bid0_q, ask0_p, ask0_q))


def handle_trade(trade):
  print('"TRADE",%d,%f,%f,%f,%f' % (trade.timestamp, trade.price, trade.qty, trade.side, 0))


def run_archive():
  flow_sub = flow_subscriber.from_archive(
      # datetime.datetime(2018, 4, 23, 0, 0),
      datetime.datetime(2018, 4, 23, 18, 0),
      machine='feed-1.aliyun-cn-hongkong',
      root_dir='/home/ec2-user/data/flow',
      topic_string=['bitmex_ws_orderBookL2_a1', 'bitmex_ws_trade_a1'])
  handler = BitmexHandler()
  flow_sub.subscribe('bitmex_ws_orderBookL2_a1', handler.on_ws_orderbook_l2)
  flow_sub.subscribe('bitmex_ws_trade_a1', handler.on_ws_trade)

  product = BitmexFuturesProduct.FromStr('BTC-USD.PERPETUAL')
  native_symbol = product.native_symbol
  print(native_symbol)
  handler.subscribe_book(native_symbol, handle_book)
  handler.subscribe_trade(native_symbol, handle_trade)

  flow_sub.start(until=datetime.datetime(2018, 4, 23, 18, 33))


def main(argv):
  run_archive()
  return 0


if __name__ == '__main__':
  sys.exit(main(sys.argv))
